package com.inspur.edp.bef.bizentity.json.operation;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonToken;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.inspur.edp.bef.bizentity.beenum.BETriggerTimePointType;
import com.inspur.edp.bef.bizentity.beenum.RequestNodeTriggerType;
import com.inspur.edp.bef.bizentity.common.BizEntityJsonConst;
import com.inspur.edp.cef.designtime.api.json.SerializerUtils;

import java.util.EnumSet;
import java.util.HashMap;
import java.util.LinkedHashMap;

import static com.fasterxml.jackson.core.JsonToken.END_ARRAY;
import static com.fasterxml.jackson.core.JsonToken.FIELD_NAME;

public class ValidatoinTriggerPointsDeserializer extends JsonDeserializer<HashMap<BETriggerTimePointType, EnumSet<RequestNodeTriggerType>>> {
    public BETriggerTimePointType currentKey;

    @Override
    public HashMap<BETriggerTimePointType, EnumSet<RequestNodeTriggerType>> deserialize(JsonParser parser, DeserializationContext ctxt) {
        HashMap<BETriggerTimePointType, EnumSet<RequestNodeTriggerType>> hashMap = createHashMap();
        if (SerializerUtils.readNullObject(parser)) {
            return hashMap;
        }
        SerializerUtils.readStartArray(parser);
        JsonToken tokentype = parser.getCurrentToken();
        if (tokentype != END_ARRAY) {
            while (parser.getCurrentToken() == tokentype) {
                readHashMap(hashMap, parser);
            }
        }
        SerializerUtils.readEndArray(parser);

        return hashMap;
    }

    private void readHashMap(HashMap<BETriggerTimePointType, EnumSet<RequestNodeTriggerType>> hashMap, JsonParser parser) {
        SerializerUtils.readStartObject(parser);
        while (parser.getCurrentToken() == FIELD_NAME) {
            String propName = SerializerUtils.readPropertyName(parser);
            readPropertyValue(hashMap, propName, parser);
        }
        SerializerUtils.readEndObject(parser);
    }

    private void readPropertyValue(HashMap<BETriggerTimePointType, EnumSet<RequestNodeTriggerType>> hashMap, String propName, JsonParser jsonParser) {
        switch (propName) {
            case BizEntityJsonConst.ValidationTriggerPointKey:
                currentKey = (BETriggerTimePointType) BizOperationDeserializer.readBETriggerTimePointType(jsonParser).toArray()[0];
                break;
            case BizEntityJsonConst.ValidationTriggerPointValue:
                EnumSet<RequestNodeTriggerType> currentValue = BizOperationDeserializer.readRequestNodeTriggerType(jsonParser);
                hashMap.put(currentKey, currentValue);
                break;
        }
    }

    private HashMap<BETriggerTimePointType, EnumSet<RequestNodeTriggerType>> createHashMap() {
        return new LinkedHashMap<BETriggerTimePointType, EnumSet<RequestNodeTriggerType>>();
    }
}
